﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace SharePointUtilitiesForDevelopers.Mapper
{
    /// <summary>
    /// A mapper that maps the xml web service response to a <see cref="SharePointList"/>.
    /// </summary>
    public class SharePointListMapper: IMapper<XElement, SharePointList>
    {

        /// <summary>
        /// Maps the source type to the target type.
        /// </summary>
        /// <param name="from">The object to map from.</param>
        /// <returns>The mapped object.</returns>
        public SharePointList Map(XElement from)
        {
            return MapList(from).SingleOrDefault();
        }

        /// <summary>
        /// Maps the source type to a list of the target type.
        /// </summary>
        /// <param name="from">From.</param>
        /// <returns></returns>
        public IEnumerable<SharePointList> MapList(XElement from)
        {
            try
            {
                var lists = SharePointMapper.MapResponseToList<SharePointList>(
                    MapInternal,
                    ele => string.Compare(ele.Name.LocalName, "List", StringComparison.InvariantCultureIgnoreCase) == 0,
                    from);

                return lists.OrderBy(list => list.Title).ToList();
            }
            catch (Exception ex)
            {
                throw new SharePointMapperException<XElement, SharePointList>(ex);
            }
        }

        /// <summary>
        /// Maps the element to a domain object.
        /// </summary>
        /// <param name="element">The element to map from.</param>
        /// <returns>The mapped object.</returns>
        private static SharePointList MapInternal(XElement element)
        {
            return new SharePointList
                       {
                           Id = SharePointXml.GetAttributeAsString(element, "ID"),
                           Title = SharePointXml.GetAttributeAsString(element, "Title"),
                           Description = SharePointXml.GetAttributeAsString(element, "Description"),
                           BaseType = SharePointXml.GetAttributeAsEnum(element, "BaseType", SharePointListBaseType.List, false),
                           Name = SharePointXml.GetAttributeAsString(element, "Name"),
                           Hidden = SharePointXml.GetAttributeAsBoolean(element, "Hidden"),
                           DefaultViewUrl = SharePointXml.GetAttributeAsString(element, "DefaultViewUrl"),
                           Version = SharePointXml.GetAttributeAsString(element, "Version"),
                           Definition = element
                       };
        }
    }
}